python创建自定义函数is |
您所在的位置:网站首页 › isnumber 函数 › python创建自定义函数is |
主要使用错误异常处理try:except:,和float(s)以及unicodedata.numeric(s)函数来处理 def is_number(s): try: float(s) # 如果能转换float,说明是个数字 return True except ValueError: pass # 占位符 try: import unicodedata # 引入Unicodedata模块 unicodedata.numeric(s) # 如果能转成numeric,说明是个数字 return True except (TypeError,ValueError): pass return False # 阿拉伯语5 print(is_number('٥')) # 中文数字亿 print(is_number('亿')) # 连续数字 print(is_number('一二三'))运行效果 True True False Process finished with exit code 0发现在处理中文连续数字的时候发生了问题 修改如下: def is_number(s): try: import unicodedata # 引入Unicodedata模块 for ch in s: unicodedata.numeric(ch) # 如果能转成numeric,说明是个数字 return True except (TypeError,ValueError): pass return False # 连续数字 print(is_number('一二三四五')) print(is_number('一二三四五上山打老虎'))运行效果 True False Process finished with exit code 0 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |